package com.jie.commonlib.support.async;

import android.os.AsyncTask;

/**
 * @author H.J.
 * @date 2020/4/7 11:17
 * @description 自定义异步任务
 * FIXME: 2020/9/29 AsyncTask谷歌官方已不建议使用，推荐使用协程
 */
@Deprecated
public class CustomAsyncTask<E,T> extends AsyncTask<E, Integer, T> {

    private final AsyncCallBack mAsyncCallBack;
    /**
     * 是否取消当前异步任务,注意取消后，将不会在执行mAsyncCallBack回调
     */
    private boolean isCancel;

    public CustomAsyncTask(AsyncCallBack asyncCallBack){
        this.mAsyncCallBack = asyncCallBack;
        // 初始化为未取消状态
        this.isCancel = false;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if (mAsyncCallBack != null && mAsyncCallBack instanceof AsyncHasProgressCallBack && !isCancel){
            if (values != null && values.length > 0){
                ((AsyncHasProgressCallBack) mAsyncCallBack).update(values[0]);
            }
        }
    }

    @Override
    protected T doInBackground(E... ts) {
        if (mAsyncCallBack != null && !isCancel){
            return (T) mAsyncCallBack.doInBackground(ts);
        }
        return null;
    }

    @Override
    protected void onPostExecute(T t) {
        super.onPostExecute(t);
        if (mAsyncCallBack != null && !isCancel){
            mAsyncCallBack.result(t);
        }
    }

    /**
     * 取消当前异步任务
     */
    public void cancel(){
        this.isCancel = true;
        if (!isCancelled()){
            cancel(true);
        }
    }
}
